package com.hack.hackathon.controller;

import com.hack.hackathon.service.UserService;
import com.hack.hackathon.util.JsonUtil;
import com.hack.hackathon.vo.PostDataVO;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Wang Yong on 16-10-29.
 */
@Controller
@RequestMapping("/data")
public class UserController{

    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.POST,value = "/postdata.do")
    public void extractNeedData(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String jsonData = IOUtils.toString(request.getInputStream(),request.getCharacterEncoding());
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>");
        System.out.println(">>>>>"+jsonData);
        try{
            PostDataVO postDataVO = JsonUtil.readValue(jsonData,PostDataVO.class);
            boolean createUser = userService.addIfNotExists(postDataVO);
            if(createUser){
                userService.addOrder(postDataVO);
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }

    @RequestMapping("/todayInfo.do")
    @ResponseBody
    public String todayInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{
        return JsonUtil.toJson(this.userService.fetchTodayInfo());
    }

}
